﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Portal.WebLogic;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.Biz;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.Web.Areas.WorkSpace.Models;
using GoodMan.Tool.Framework;

namespace GoodMan.Portal.Web.Areas.WorkSpace.Controllers
{
    /// <summary>
    /// 校级财务管理人员
    /// </summary>
    [ErrorHandle]
    [Warp]
    [Auth(UserRole.Officer)]
    public class OfficerController : Controller
    {
        //
        // GET: /WorkSpace/Officer/

        public ActionResult Index()
        {
            return View();
        }

        #region 用户

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterUserInfoList(UserModel model, int page = 0)
        {
            model.SystemRole = 1;
            ViewBag.UserList = UserBiz.GetAllUserByWhere(page, 10, model.SystemRole, model.FloorId, model.Gender, -1, model.Dormitory, model.NickName, model.RealName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            ViewBag.SearchModel = model;
            return View();
        }


        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UserInfo(string u, int page = 0, int r = 0)
        {
            ViewBag.page = page;
            ViewBag.Register = r;
            ViewBag.User = new User().Find(u);
            return View();
        }
        #endregion

        #region 订单管理

        #region 订单统计
        public ActionResult OrdersStatistics(int page = 0, string realName = "", string dtstart = "", string dtend = "", int status = -1)
        {
            int orderCount = 0;
            decimal totalPrice = 0.00m;
            var orderList = OrderBiz.OrderQuery(UserRole.Officer, -1, realName, dtstart, dtend, status,false, page, 10, ref orderCount, ref totalPrice);
            ViewBag.OrderList = orderList;

            #region 回填数据
            ViewBag.realName = realName;
            ViewBag.dtstart = dtstart;
            ViewBag.dtend = dtend;
            ViewBag.status = status;
            ViewBag.orderCount = orderCount;
            ViewBag.totalPrice = totalPrice;
            #endregion
            return View();
        }

        public ActionResult OrderDetail(int id)
        {
            Order order = new Order().Find(id.ToString());
            List<OrderDetail> orderDetailList = new OrderDetail().FindAll(c => c.OrderId == id);
            string name = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(name);
            ViewBag.User = user;
            ViewBag.Order = order;
            ViewBag.OrderDetail = orderDetailList;
            ViewBag.OrderHistory = new OrderHistory().FindAll(c => c.OrderId == order.Id);
            return View();
        }
        #endregion

        #region 退款待处理
        /// <summary>
        /// 查询【申请退款】列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult WaitForHandleOrder(int page = 0)
        {
            var refundList = OrderBiz.GetApplyRefundList(1, page, 10);
            ViewBag.RefundList = refundList;
            return View();
        }

        /// <summary>
        /// 按条件查询【申请退款】列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult WaitForHandleOrder(string applyname, string domitoryid, string dtstart, string dtend, int page = 0)
        {
            var refundList = OrderBiz.ApplyRefundQuery(applyname, domitoryid, dtstart, dtend, 1, page, 10);
            ViewBag.RefundList = refundList;
            return View();
        }

        public ActionResult ModifyRefund(int id = 0, int status = 0, int page = 0)
        {
            ViewBag.isSuccess = OrderBiz.ModifyRefundStatus(id, status);
            return Redirect("/WorkSpace/Officer/WaitForHandleOrder?page=" + page);
        }

        #endregion

        #endregion

        public ActionResult UserRebate(int id = 0)
        {
            var list = RebateReportBiz.GetLastMonthOrders();
            if (list != null)
            {
                var data = list.GroupBy(c => c.DormitoryId);
                var dormitoryList = new List<Dormitory>();

                foreach (var item in data)
                {
                    var dormitory = new Dormitory().Find(item.Key.ToString());
                    dormitory.RebateReportList = list.Where(c => c.DormitoryId == item.Key).ToList();
                    dormitoryList.Add(dormitory);
                }
                ViewBag.LastMonthOrders = dormitoryList;
            }
            else
            {
                ViewBag.LastMonthOrders = null;
            }
            if (id > 0)
            {
                ViewBag.Message = "保存成功！";
            }
            return View();
        }

        [HttpPost]
        public ActionResult SaveUserRebate(string userNames, string year, string month)
        {
            try
            {
                if (userNames != null && userNames.Length > 0)
                {
                    var reportList = new List<RebateReport>();
                    foreach (var userName in userNames.Split(','))
                    {
                        if (userName != "")
                        {
                            var report = new RebateReport();
                            string successOrdersStr = Request.Form["SuccessOrders" + userName].ToString();
                            int successOrders = int.Parse(successOrdersStr == "" ? "0" : successOrdersStr);
                            string cancelOrdersStr = Request.Form["CancelOrders" + userName].ToString();
                            int cancelOrders = int.Parse(cancelOrdersStr == "" ? "0" : cancelOrdersStr);
                            string successMoneyStr = Request.Form["SuccessMoney" + userName].ToString();
                            decimal successMoney = decimal.Parse(successMoneyStr == "" ? "0" : successMoneyStr);
                            string rebateStr = Request.Form["Rebate" + userName].ToString();
                            decimal rebate = decimal.Parse(rebateStr == "" ? "0" : rebateStr);
                            string bonusStr = Request.Form["bonus" + userName].ToString();
                            decimal bonus = decimal.Parse(bonusStr == "" ? "0" : bonusStr);

                            string floorIdStr = Request.Form["DormitoryId" + userName].ToString();
                            int floorId = int.Parse(floorIdStr == "" ? "0" : floorIdStr);

                            report.Bonus = bonus;
                            report.CreateDate = DateTime.Now;
                            report.CreateUser = System.Web.HttpContext.Current.User.Identity.Name;
                            report.DealOrders = successOrders + cancelOrders;
                            report.DormitoryId = floorId;
                            report.Month = month.PadLeft(2, '0');
                            report.Rebate = rebate;
                            report.SuccessMoney = successMoney;
                            report.SuccessOrders = successOrders;
                            report.UserName = userName;
                            report.Year = year;

                            reportList.Add(report);

                        }
                    }
                    if (reportList != null && reportList.Count > 0)
                    {
                        //执行插入操作
                        foreach (var item in reportList)
                        {
                            var temp = new RebateReport().Find(c => c.UserName == item.UserName && c.Year == item.Year && c.Month == item.Month);
                            if (temp != null)
                            {
                                temp.Bonus = item.Bonus;
                                temp.PostModify();
                            }
                            else
                            {
                                item.PostAdd();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {


            }

            return Redirect("/WorkSpace/Officer/UserRebate/1");
        }

        public ActionResult UserRebateReport(string startYear, string startMonth, string endYear, string endMonth,int page=0)
        { 
            int currentYear = DateTime.Now.Year;
            List<Object> objList = null;

            objList = new List<object>();
            objList.Add(new { value = 0, name = "请选择" });
            for (int i = 2013; i <= currentYear; i++)
            {

                List<object> subList = null;

                subList = new List<object>();
                subList.Add(new { value = 0, name = "请选择" });
                for (int j = 1; j < 13; j++)
                {
                    subList.Add(new { value = j.ToString().PadLeft(2, '0'), name = j.ToString().PadLeft(2, '0') });
                } 
                objList.Add(new { value = i.ToString(), name = i.ToString(), children = subList });

            }

            ViewBag.MonthList = objList.ToJson();
            var list = RebateReportBiz.GetRebateReport(startYear, startMonth, endYear, endMonth, page,20);
            
              ViewBag.data = list;
            

            DateTime date = DateTime.Now.AddMonths(-1);
            if (startYear == null || startYear == "")
            {
                startYear = date.Year.ToString();
            }
            if (startMonth == null || startMonth == "")
            {
                startMonth = date.Month.ToString().PadLeft(2, '0');
            }
            if (endYear == null || endYear == "")
            {
                endYear = date.Year.ToString();
            }
            if (endMonth == null || endMonth == "")
            {
                endMonth = date.Month.ToString().PadLeft(2, '0');
            }

            ViewBag.startYear = startYear;
            ViewBag.startMonth = startMonth;
            ViewBag.endYear = endYear;
            ViewBag.endMonth = endMonth;

            return View();
        }
        [HttpPost]
        public ActionResult SearchRebateReport(string startYear, string startMonth, string endYear, string endMonth)
        {
            return Redirect("/WorkSpace/Officer/UserRebateReport?startYear=" + startYear + "&startMonth=" + startMonth + "&endYear=" + endYear + "&endMonth=" + endMonth);
        }

        #region 个人信息
        /// <summary>
        /// 个人信息首页
        /// </summary>
        /// <returns></returns>
        public ActionResult MyInfo()
        {
            string userName = HttpContext.User.Identity.Name;
            ViewBag.UserModel = new User().Find(userName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MyInfo(UserModel model)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改个人信息失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改信息失败！";
                    return View();
                }
                ViewBag.UserModel = user;
                ViewBag.Error = "";
            }
            ViewBag.UserModel = user;
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        public ActionResult Secret()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Confirm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Secret(string Confirm)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("管理员：{0}修改密码失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return View();
        }
        #endregion
    }
}
